// pages/activity/newmbrActivity/newmbrActivity.js
const bannerService = require('../../../../api/bannerService.js')
const newmbrActivityService = require('../../../../api/newmbrActivityService.js')
const shopcartService = require('../../../../api/shopcartService.js')
const util = require('../../../../utils/utils.js')

//获取应用实例
const app = getApp()

Page({

  /**
   * 页面的初始数据
   */
  data: {
    banners: [],
    goodsList: []
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    const self = this
    // 判断globalData.storeInfo有没有数据，有数据，则使用选择的门店数据，没有，则根据当前地理位置获取最近门店
    if (app.globalData.storeInfo) {
      self.setData({
        'storeId': app.globalData.storeInfo.id,
      })
      this.getNewmbrActivity(app.globalData.storeInfo.id)
      this.getBannerList(app.globalData.storeInfo.id)
    } else {
      // 获取当前地理位置，然后筛选出最近的门店，根据当前门店获取门店的商品
      wx.getLocation({
        type: 'wgs84',
        success: function (res) {
          var latitude = res.latitude
          var longitude = res.longitude
          var speed = res.speed
          var accuracy = res.accuracy
          try {
            var tempAllStores = wx.getStorageSync('wj_allStores'); // 获取缓存的所有门店
            if (tempAllStores) {
              // Do something with return value
              let tempIndex = self.getNearestStore(tempAllStores, latitude, longitude);
              app.globalData.storeInfo = tempAllStores[tempIndex];
              // 获取当前门店的新人专享活动
              self.getNewmbrActivity(tempAllStores[tempIndex].id)
              self.getBannerList(tempAllStores[tempIndex].id)
            } else {
              // 查询所有门店
              storeService.queryList().then(res => {
                var allStores = res;
                try {
                  wx.setStorageSync('wj_allStores', allStores)
                } catch (e) {
                  console.log(e)
                }
                let tempIndex = self.getNearestStore(allStores, latitude, longitude);
                return allStores[tempIndex]
              }).then(res => {
                app.globalData.storeInfo = res;
                self.getNewmbrActivity(res.id)
                self.getBannerList(res.id)
              })
            }
          } catch (e) {
            // Do something when catch error
          }
        }
      })
    }
    if (self.options.mobile && self.options.mobile != '' && self.options.mobile != undefined) {
      const mobile = self.options.mobile
      try {
        wx.setStorageSync('wj_sharingId', mobile)
      } catch (e) {}
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    if (app.globalData.userInfo && app.globalData.userInfo.member) {
      let memberId = app.globalData.userInfo.member.id
      return {
        path: '/pages/mallModule/activity/newmbrActivity/newmbrActivity?mobile=' + memberId
      }
    }
  },

  // 获取最近的一家门店
  getNearestStore: function (allStores, latitude, longitude) {
    var distanceArr = [];
    allStores.forEach(item => {
      let dis = util.distance(latitude, longitude, item.latitude, item.longitude);
      distanceArr.push(dis);
    })
    // 计算最小值
    const minN = Math.min.apply(Math, distanceArr);
    let tempIndex = 0;
    for (var i = 0; i < distanceArr.length; i++) {
      if (minN === distanceArr[i]) {
        tempIndex = i;
        break;
      }
    }
    this.setData({
      store: allStores[tempIndex].name,
      storeId: allStores[tempIndex].id
    })
    return tempIndex;
  },

  /**
   * 获取banner图片
   */
  getBannerList: function (storeId) {
    bannerService.getStoreBannerList('NEWMBRACTIVITYADSENSE', storeId).then(res => {
      console.log(res)
      this.setData({
        banners: res
      })
    })
  },

  /**
   * 获取新用户专享活动
   * @param storeId 门店id
   */
  getNewmbrActivity: function (storeId) {
    const that = this
    newmbrActivityService.getAll(storeId).then(res => {
      console.log(res)
      let tempList = []
      for (let i = 0; i < res.length; i++) {
        const item = res[i];
        item.products.forEach(ele => {
          let tempEle = {
            ...ele
          }
          let specifications = []
          let produtlabel = []
          let promotions = []
          if (ele.labels && ele.labels.length > 0) {
            ele.labels.forEach(item => {
              if (item.type === 'GOODSLABEL') {
                produtlabel.push(item)
              } else if (item.type === 'PROMOTIONLABEL') {
                promotions.push(item)
              }
            })
          }
          if (ele.propertys && ele.propertys.length > 0) {
            for (let i = 0; i < ele.propertys.length; i++) {
              const temp = ele.propertys[i];
              if (temp.propertyName === '规格') {
                specifications = temp.propertyValue
                break
              }
            }
          }
          tempEle = {
            ...tempEle,
            specifications: specifications,
            produtlabel: produtlabel,
            promotions: promotions
          }
          tempList.push(tempEle)
        })
        break;
      }
      that.setData({
        goodsList: tempList
      })
    })
  },

  addShopcartEmpty: function () {

  },

  // 添加购物车
  addShopcart: function (val) {
    console.log(val)
    const balance = val.detail.target.dataset.balance
    const activityId = val.detail.target.dataset.activityid
    const productId = val.detail.target.dataset.id
    let sharingPersonId = ''
    if (balance > 0) {
      let postData = {
        storeId: this.data.storeId,
        lists: [{
          count: 1,
          newmbrActivityId: activityId,
          productId: productId
        }]
      }
      console.log(postData)
      shopcartService.cateringAdd(postData).then(res => {
        wx.showToast({
          title: '加入购物车成功~',
          icon: 'none',
          duration: 2000
        })
      }).catch(err => {
        if (err.code === 39008) {
          wx.showToast({
            title: '您已购买过专享商品~',
            icon: 'none',
            duration: 2000
          })
        } else {
          wx.showToast({
            title: err.message,
            icon: 'none',
            duration: 2000
          })
        }
      })
    } else {
      wx.showToast({
        title: '门店补货中，去其他门店看看吧~',
        icon: 'none',
        duration: 2000
      })
    }
  },

  // banner跳转
  bannerJumping: function (e) {
    const that = this
    let bannerId = e.currentTarget.dataset.id
    const bannerList = that.data.banners
    let advertisementInfo = null
    bannerList.forEach(item => {
      if (item.id === bannerId) {
        advertisementInfo = item
      }
    });
    console.log(advertisementInfo)
    that.toAdPage(advertisementInfo, 'banner')
  },

  // 前往广告页
  toAdPage: function (pageInfo, pageType) {
    const that = this
    if (pageInfo.linkType === 'APP') {
      // 应用
      // 判断跳转模块
      if (pageInfo.appReturnType === 'MIAOSHA') {
        wx.navigateTo({
          url: '../../activity/seckill/seckill'
        })
      } else if (pageInfo.appReturnType === "RECHARGE") {
        wx.navigateTo({
          url: '../../myCard/recharge/recharge'
        })
      } else if (pageInfo.appReturnType === "MEAL") {
        //  餐饮
      } else if (pageInfo.appReturnType === "RECEIVECOUPON") {
        // 领券中心
        wx.navigateTo({
          url: '../../coupon/couponCenter/couponCenter'
        })
      } else if (pageInfo.appReturnType === "ADVANCE_SELL_PRODUCT") {
        // 预售商品
        wx.navigateTo({
          url: '../../activity/advanceSell/advanceSell'
        })
      } else if (pageInfo.appReturnType === "TEAM_BUYING") {
        // 团购
        wx.navigateTo({
          url: '../../fightGroup/fightGroup/fightGroup'
        })
      } else if (pageInfo.appReturnType === "SCOREMALL") {
        // 积分商场
        wx.navigateTo({
          url: '../../score/scoreMall/scoreMall'
        })
      } else if (pageInfo.appReturnType === "INVITE_MEMBER") {
        // 邀请好友
        wx.navigateTo({
          url: '../../invite/invite'
        })
      } else if (pageInfo.appReturnType === "MEMBER_CARD") {
        // 会员卡
        wx.navigateTo({
          url: '../../myCard/memberCard/memberCard'
        })
      } else if (pageInfo.appReturnType === "MY_COUPON") {
        // 我的优惠券
        wx.navigateTo({
          url: '../../coupon/myCoupon/myCoupon'
        })
      } else if (pageInfo.appReturnType === "NEWMBR") {
        // 新用户专享
        wx.navigateTo({
          url: '../../activity/newmbrActivity/newmbrActivity'
        })
      }
    } else if (pageInfo.linkType === 'GRADPRODUCT') {
      // 秒杀商品
      wx.navigateTo({
        url: '../../goods/goodsDetail/goodsDetail?productId=' + pageInfo.productId + '&storeId=' + app.globalData.storeInfo.id + '&type=secondkill'
      })
    } else if (pageInfo.linkType === 'PRODUCT') {
      // 商品 
      wx.navigateTo({
        url: '../../goods/goodsDetail/goodsDetail?productId=' + pageInfo.productId + '&storeId=' + app.globalData.storeInfo.id + '&type=normal'
      })
    } else if (pageInfo.linkType === 'TEAMPRODUCT') {
      // 拼团商品 
      wx.navigateTo({
        url: '../../goods/goodsDetail/goodsDetail?productId=' + pageInfo.teamActivityId + '&storeId=' + app.globalData.storeInfo.id + '&type=group'
      })
    } else if (pageInfo.linkType === 'COUPONACTIVITYDETAILS') {
      if (app.globalData.userInfo) {
        if (app.globalData.userInfo.member) {
          wx.navigateTo({
            url: '../../coupon/couponDetails/couponDetails?couponActivityId=' + pageInfo.couponActivityId + '&type=assign&isExternal=false'
          })
        } else {
          wx.showToast({
            title: '您还不是会员，请绑定手机号成为会员~',
            icon: 'none',
            duration: 2000
          })
          setTimeout(() => {
            that.handlePopupPhone()
          }, 2000);
        }
      }
    } else if (pageInfo.linkType === 'URL') {
      // 链接
      let url = null
      if (pageType === 'activity') {
        url = pageInfo.linkUrl
      } else if (pageType === 'banner') {
        url = pageInfo.link
      }
      var index = '?'
      let webUrl = url
      if (url.indexOf(index) > -1) {
        webUrl = webUrl + '&storeId=' + this.data.storeId + '&type=normal'
      }
      let urlData = {
        url: encodeURIComponent(webUrl)
      }
      console.log(webUrl, urlData)
      let jsonUrl = JSON.stringify(urlData)
      wx.navigateTo({
        url: '../../advertising/advertising?webUrl=' + jsonUrl
      })
    } else {

    }
  },
  // 前往首页
  toHome: function () {
    wx.switchTab({
      url: '../../index/index',
    })
  },

  /**
   * 前往商品详情 
   */
  toGoodsDetail: function (val) {
    console.log(val)
    const that = this
    if (val.currentTarget.dataset.balance > 0) {
      if (val.currentTarget.dataset.goodsnum > 0) {
        let activityId = val.currentTarget.dataset.activityid
        let goodsId = val.currentTarget.dataset.goodsid
        let goods = null
        for (let i = 0; i < that.data.goodsList.length; i++) {
          const item = that.data.goodsList[i];
          if (item.productId === goodsId) {
            goods = item
          }
        }
        let goodsDetail = JSON.stringify(goods)
        let url = '../../goodsDetail/goodsDetail?productId=' + goodsId + '&goodsDetail=' + goodsDetail + '&type=newmbr'
        if (that.options.mobile) {
          url = url + '&mobile=' + that.options.mobile
        }
        wx.navigateTo({
          url: url
        })
      } else {
        wx.showToast({
          title: '您来晚了，已经被抢光了',
          icon: 'none',
          duration: 2000
        })
      }
    } else {
      if (val.currentTarget.dataset.goodsnum > 0) {
        wx.showModal({
          title: '提示',
          content: '门店正在努力补货中,去其他门店看看吧~',
          success: function (res) {
            if (res.confirm) {
              wx.switchTab({
                url: '../index/index'
              })
            } else if (res.cancel) {

            }
          }
        })
      } else {
        wx.showToast({
          title: '您来晚了，已经被抢光了',
          icon: 'none',
          duration: 2000
        })
      }
    }
  },
})